<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>表单处理</title>
</head>
<body>
<div id="root">

</div>
</body>
<script src="js/old/babel.min.js"></script>
<script src="js/old/react.development.js"></script>
<script src="js/old/react-dom.development.js"></script>
<script type="text/babel">

  // 非受控表单
  class Login extends React.Component {

    handleSubmit = e => {
      e.preventDefault()
      const {username, password} = this
      console.log({username: username.value, password: password.value})
    }

    render() {
      return (
        <React.Fragment>
          <form onSubmit={this.handleSubmit} action="#" method="post">
            <fieldset>
              <label htmlFor="username">
                用户名：<input ref={c => this.username = c} type="text" name="username" id="username"/> <br/>
              </label>
              <label htmlFor="password">
                密&nbsp;&nbsp;码：<input ref={c => this.password = c} type="password" name="password" id="password"/> <br/>
              </label>
              <input type="submit" value="登录"/>
            </fieldset>
          </form>
        </React.Fragment>
      )
    }
  }


  // 受控表单
  class Login2 extends React.Component {

    // 受控表单, 状态在组件内部
    state = {
      username: '',
      password: '',
    }

    handleSubmit = e => {
      e.preventDefault()
      const {username, password} = this.state
      console.log({username, password})
    }

    // 更新表单数据
    saveFormData = key => e => this.setState({[key]: e.target.value})


    render() {
      return (
        <React.Fragment>
          <form onSubmit={this.handleSubmit} action="#" method="post">
            <fieldset>
              <label htmlFor="username">
                用户名：<input onChange={this.saveFormData('username')} type="text" name="username" id="username"/> <br/>
              </label>
              <label htmlFor="password">
                密&nbsp;&nbsp;码：<input onChange={this.saveFormData('password')} type="password" name="password" id="password"/> <br/>
              </label>
              <input type="submit" value="登录"/>
            </fieldset>
          </form>
        </React.Fragment>
      )
    }
  }

  ReactDOM.render(<Login2/>, document.getElementById('root'))
</script>
</html>